<template>
  <div class="user-container">
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button
        type="danger"
        :disabled="!multipleSelection.length"
        @click="handleBatchDelete"
        >批量删除</el-button
      >
    </div>

    <el-table
      v-loading="loading"
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="80" />
      <el-table-column prop="userName" label="用户名" />
      <el-table-column prop="fullName" label="姓名" />
      <el-table-column prop="phoneNumber" label="手机号" />
      <el-table-column label="头像" width="100">
        <template #default="scope">
          <el-avatar
            v-if="scope.row.avatarAddress"
            :src="scope.row.avatarAddress"
          />
          <el-avatar v-else :icon="UserFilled" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户表单对话框 -->
    <user-form
      v-if="formVisible"
      v-model="formVisible"
      :form-type="formType"
      :user-data="currentUser"
      @submit-success="fetchUserList"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { UserFilled } from "@element-plus/icons-vue";
import userApi from "@/api/user";
import UserForm from "./components/UserForm.vue";

// 数据加载状态
const loading = ref(false);
// 用户列表数据
const userList = ref([]);
// 选中的用户列表（用于批量操作）
const multipleSelection = ref([]);
// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
// 表单对话框可见性
const formVisible = ref(false);

// 表单类型（add/edit）
const formType = ref("");
// 当前操作的用户数据
const currentUser = ref({});

// 页面操作模式（add/edit/view）
const pageMode = ref("");

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    const response = await userApi.getUserList(
      pagination.value.pageNum,
      pagination.value.pageSize
    );

    userList.value = response.list || [];
    pagination.value.total = response.total || 0;
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection;
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.pageNum = 1; // 重置为第一页
  fetchUserList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.pageNum = page;
  fetchUserList();
};

// 添加用户
const handleAdd = () => {
  currentUser.value = {}; // 清空当前用户数据
  formType.value = "add";
  formVisible.value = true;
};

// 编辑用户
const handleEdit = (row) => {
  currentUser.value = { ...row }; // 复制用户数据
  formType.value = "edit";
  formVisible.value = true;
};

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户"${row.userName}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await userApi.deleteUser(row.id);
        ElMessage.success("删除成功");
        fetchUserList(); // 刷新列表
      } catch (error) {
        console.error("删除用户失败:", error);
        ElMessage.error("删除用户失败");
      }
    })
    .catch(() => {
      // 取消删除，不做处理
    });
};

// 批量删除用户
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的用户");
    return;
  }

  const names = multipleSelection.value.map((item) => item.userName).join("、");
  ElMessageBox.confirm(
    `确定要删除选中的${multipleSelection.value.length}个用户(${names})吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      // 实际场景中，如果后端支持批量删除，可以一次请求；否则需要循环删除
      try {
        const promises = multipleSelection.value.map((item) =>
          userApi.deleteUser(item.id)
        );
        await Promise.all(promises);
        ElMessage.success("批量删除成功");
        fetchUserList(); // 刷新列表
      } catch (error) {
        console.error("批量删除用户失败:", error);
        ElMessage.error("批量删除用户失败");
      }
    })
    .catch(() => {
      // 取消删除，不做处理
    });
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "";
  // 简单格式化，实际项目中可以使用dayjs等库进行更强大的格式化
  const date = new Date(dateTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")} ${String(
    date.getHours()
  ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}:${String(
    date.getSeconds()
  ).padStart(2, "0")}`;
};

// 组件挂载时获取数据
onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
